<template>
	<view class="container" v-if="!loading">
		<view class="main" v-if="store">
			<view class="nav">
				<view class="header">
					<view class="left">
						<view class="store-name" @tap="selectStore">
							<text>{{ store.storeName }}</text>
							<tui-icon style="margin-left:16rpx" name="arrowright" :size="32" unit="rpx"></tui-icon>
							<!-- <view class="iconfont iconarrow-right"></view> -->
						</view>
					</view>

					<view class="right">
						<view class="distance">
							<text>距离{{store.distance}}km</text>
						</view>
					</view>
				</view>
				<view class="coupon" @tap="storeInfo">
					<text class="title">{{store.storeSummary}}</text>
					<view class="iconfont iconarrow-right"></view>
				</view>
			</view>
			<view class="content">
				<scroll-view class="menus" :scroll-into-view="menuScrollIntoView" scroll-with-animation scroll-y>
					<view class="wrapper">
						<view class="menu" :id="`menu-${item.id}`" :class="{'current': item.id === currentCateId}" v-for="(item, index) in tickets"
						 :key="index" @tap="handleMenuTap(item.id)">
							<!-- <image :src="item.cateImg" class="image" mode="widthFix"></image> -->
							<text>{{ item.cateName }}</text>
							<view class="dot" v-show="menuCartNum(item.id)">{{ menuCartNum(item.id) }}</view>
						</view>
					</view>
				</scroll-view>
				<!-- goods list begin -->
				<scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="cateScrollTop" @scroll="handleGoodsScroll">
					<view class="wrapper">
						<swiper class="ads" id="ads" autoplay :interval="3000" indicator-dots>
							<swiper-item v-for="(item, index) in ads" :key='index'>
								<image :src="item.image"></image>
							</swiper-item>
						</swiper>
						<view class="list">
							<!-- category begin -->
							<view class="category" v-for="(item, index) in tickets" :key="index" :id="`cate-${item.id}`">
								<view class="title">
									<text>{{ item.cateName }}</text>
									<image :src="item.cateIconImg" class="icon"></image>
								</view>
								<view class="items">
									<!-- 商品 begin -->
									<view class="good" v-for="(good, key) in item.tickets" :key="key">
										<image :src="good.productImg" class="image" @tap="showGoodDetailModal(item, good)"></image>
										<view class="right">
											<text class="name">{{ good.productName }}</text>
											<text class="tips">{{ good.introduction }}</text>
											<view class="price_and_action">
												<text class="price">￥{{ good.salePrice }}</text>
												<view class="btn-group" v-if="good.specConfig == 1">
													<button type="primary" class="btn property_btn" hover-class="none" size="mini" @tap="showGoodDetailModal(item, good)">
														选规格
													</button>
													<view class="dot" v-show="goodCartNum(good.id)">{{ goodCartNum(good.id) }}</view>
												</view>
												<view class="btn-group" v-else>
													<button type="default" v-show="goodCartNum(good.id)" plain class="btn reduce_btn" size="mini" hover-class="none"
													 @tap="handleReduceFromCart(item, good)">
														<view class="iconfont iconsami-select"></view>
													</button>
													<view class="number" v-show="goodCartNum(good.id)">{{ goodCartNum(good.id) }}</view>
													<button type="primary" class="btn add_btn" size="min" hover-class="none" @tap="handleAddToCart(item, good, 1)">
														<view class="iconfont iconadd-select"></view>
													</button>
												</view>
											</view>
										</view>
									</view>
									<!-- 商品 end -->
								</view>
							</view>
							<!-- category end -->
						</view>
					</view>
				</scroll-view>
				<!-- goods list end -->
			</view>
			<!-- content end -->
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="cart.length > 0">
				<view class="mark">
					<image src="/static/images/menu/cart.png" class="cart-img" @tap="openCartPopup"></image>
					<view class="tag">{{ getCartGoodsNumber }}</view>
				</view>
				<view class="price">￥{{ getCartGoodsPrice }}</view>
				<button type="primary" class="pay-btn" @tap="toPay">去结算
				</button>
			</view>
			<!-- 购物车栏 end -->
		</view>
		<!-- 商品详情模态框 begin -->
		<modal :show="goodDetailModalVisible" class="good-detail-modal" color="#5A5B5C" width="90%" custom padding="0rpx"
		 radius="12rpx">
			<view class="cover">
				<image v-if="good.productImg" :src="good.productImg" class="image" :mode="aspectFit"></image>
				<view class="btn-group">
					<image src="/static/images/menu/share-good.png"></image>
					<image src="/static/images/menu/close.png" @tap="closeGoodDetailModal"></image>
				</view>
			</view>
			<scroll-view class="detail" scroll-y>
				<view class="wrapper">
					<view class="basic">
						<view class="name">{{ good.productName }}</view>
						<view class="tips">{{ good.introduction }}</view>
					</view>
					<!-- <view class="labels">
						<tui-tag class="label" v-for="(label, index) in good.tags" :key="index" margin="20rpx 20rpx 0 0" shape="circle" type="warning">{{ label.name }}</tui-tag>
					</view> -->
					<view class="properties" v-if="good.specConfig == 1">
						<view class="property" v-for="(item, index) in good.property" :key="index">
							<view class="title">
								<text class="name">{{ item.name }}</text>
								<view class="desc" v-if="item.desc">({{ item.desc }})</view>
							</view>
							<view class="values">
								<view class="value" v-for="(value, key) in item.values" :key="key" :class="{'default': value.is_default}" @tap="changePropertyDefault(index, key)">
									{{ value.value }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="action">
				<view class="left">
					<view class="price">￥{{ good.salePrice }}</view>
					<view class="props" v-if="getGoodSelectedProps(good)">
						{{ getGoodSelectedProps(good) }}
					</view>
				</view>
				<view class="btn-group">
					<button type="default" plain class="btn" size="mini" hover-class="none" @tap="handlePropertyReduce">
						<view class="iconfont iconsami-select"></view>
					</button>
					<view class="number">{{ good.number }}</view>
					<button type="primary" class="btn" size="min" hover-class="none" @tap="handlePropertyAdd">
						<view class="iconfont iconadd-select"></view>
					</button>
				</view>
			</view>
			<view class="add-to-cart-btn" @tap="handleAddToCartInModal">
				<view>加入购物车</view>
			</view>
		</modal>
		<!-- 商品详情模态框 end -->
		<!-- 购物车详情popup -->
		<popup-layer direction="top" :show-pop="cartPopupVisible" class="cart-popup">
			<template slot="content">
				<view class="top">
					<text @tap="handleCartClear">清空</text>
				</view>
				<scroll-view class="cart-list" scroll-y>
					<view class="wrapper">
						<view class="item" v-for="(item, index) in cart" :key="index">
							<view class="left">
								<view class="name">{{ item.name }}</view>
								<view class="props"></view>
							</view>
							<view class="center">
								<text>￥{{ item.price }}</text>
							</view>
							<view class="right">
								<button type="default" plain size="mini" class="btn" hover-class="none" @tap="handleCartItemReduce(index)">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">{{ item.number }}</view>
								<button type="primary" class="btn" size="min" hover-class="none" @tap="handleCartItemAdd(index)">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</popup-layer>
		<!-- 购物车详情popup -->
		<tui-modal :show="errorModel" :maskClosable="false" :button="errorModelBtn" @click="handleClick" @cancel="handleClick"
		 title="地理位置获取超时" content="获取地理位置失败,如需买票请手动选择门店"></tui-modal>
	</view>
	<view class="loading" v-else>
		<tui-loadmore :index="3" type="orange" class="tips"></tui-loadmore>
	</view>

</template>

<script>
	import modal from '@/components/modal/modal'
	import popupLayer from '@/components/popup-layer/popup-layer'
	import tuiModal from "@/components/thorui/tui-modal/tui-modal"
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex'

	import {
		getCurrent
	} from "@/api/store";
	import {
		getCategory
	} from "@/api/ticket";
	
	import {
		addCart
	} from "@/api/order.js";

	export default {
		components: {
			modal,
			popupLayer,
			tuiModal
		},
		data() {
			return {
				tickets: [], //所有门票
				ads: [{
						image: 'http://dev-1256206693.cos.ap-beijing.myqcloud.com/upload/20210105/1baeee01a05a273297c65145c2b6398b.jpg'
					},
					{
						image: 'http://dev-1256206693.cos.ap-beijing.myqcloud.com/upload/20210105/a2da1787914b4605e625b14c920a9755.jpg'
					}
				],
				loading: true,
				parentCateId: "1342382258693447681",
				currentCateId: 0, //默认分类
				cateScrollTop: 0,
				menuScrollIntoView: '',
				cart: [], //购物车
				goodDetailModalVisible: false, //是否饮品详情模态框
				good: {}, //当前饮品
				category: {}, //当前饮品所在分类
				cartPopupVisible: false,
				sizeCalcState: false,
				store: null,
				address: "",
				errorModel: false,
				errorModelBtn: [{
						text: '取消',
						type: 'gray'
					},
					{
						text: '选择门店',
						type: 'warning'
					}
				]
			}
		},
		async onLoad() {
			this.$eventHub.$on('emit', (data) => {
				this.store = data
				this.setCurrentStoreId(this.store.id);
				this.setCurrentStore(this.store);
				this.getTicketCategory();
				uni.setStorageSync('cart', null)
				this.cart = [];
			});
		},
		onShow: function() {
			if(!this.store){
				this.getCurrentStore()
			}
		},
		computed: {
			...mapGetters(['isLogin', 'userInfo', 'currentLocation']),
			goodCartNum() { //计算单个饮品添加到购物车的数量
				return (id) => this.cart.reduce((acc, cur) => {
					if (cur.id === id) {
						return acc += cur.number
					}
					return acc
				}, 0)
			},
			menuCartNum() {
				return (id) => this.cart.reduce((acc, cur) => {
					if (cur.cate_id === id) {
						return acc += cur.number
					}
					return acc
				}, 0)
			},
			getCartGoodsNumber() { //计算购物车总数
				return this.cart.reduce((acc, cur) => acc + cur.number, 0)
			},
			getCartGoodsPrice() { //计算购物车总价
				return this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0)
			}
			// disabledPay() { //是否达到起送价
			// 	return this.orderType == 'takeout' && (this.getCartGoodsPrice < this.store.min_price) ? true : false
			// },
			// spread() { //差多少元起送
			// 	if (this.orderType != 'takeout') return
			// 	return parseFloat((this.store.min_price - this.getCartGoodsPrice).toFixed(2))
			// }
		},
		methods: {
			...mapActions(['getCurrentLocation']),
			...mapMutations(['setCurrentStoreId','setCurrentStore']),
			
			getCurrentStore(){
				this.loading = true
				getCurrent(this.currentLocation.latitude, this.currentLocation.longitude).then(res => {
					if (JSON.stringify(res.data) == "{}") {
						this.loading = false;
						this.errorModel = true;
					} else {
						this.store = res.data;
						this.setCurrentStoreId(this.store.id);
						this.setCurrentStore(this.store);
						this.getTicketCategory();
						uni.setStorageSync('cart', null)
						this.cart = [];
					}
				});
			},
			selectStore() {
				uni.navigateTo({
					url: '/pages/store/list'
				})
			},
			storeInfo() {
				uni.navigateTo({
					url: '/pages/store/index?id=' + this.store.id
				})
			},
			getTicketCategory() {
				let that = this;
				getCategory(that.parentCateId, that.store.id).then(res => {
					that.tickets = res.data;
					if (res.data.length > 0) {
						that.currentCateId = res.data[0].id;
					}
					that.loading = false;
				}, error => {
					that.loading = false;
					console.log(error);
				});
			},
			handleMenuTap(id) { //点击菜单项事件
				if (!this.sizeCalcState) {
					this.calcSize()
				}

				this.currentCateId = id
				this.$nextTick(() => this.cateScrollTop = this.tickets.find(item => item.id == id).top)
			},
			handleGoodsScroll({
				detail
			}) { //商品列表滚动事件
				if (!this.sizeCalcState) {
					this.calcSize()
				}
				const {
					scrollTop
				} = detail
				let tabs = this.tickets.filter(item => item.top <= scrollTop).reverse()
				if (tabs.length > 0) {
					this.currentCateId = tabs[0].id
				}
			},
			calcSize() {
				let h = 10

				let view = uni.createSelectorQuery().select('#ads')
				view.fields({
					size: true
				}, data => {
					h += Math.floor(data.height)
				}).exec()

				this.tickets.forEach(item => {
					let view = uni.createSelectorQuery().select(`#cate-${item.id}`)
					view.fields({
						size: true
					}, data => {
						item.top = h
						h += data.height
						item.bottom = h
					}).exec()
				})

				this.sizeCalcState = true
			},
			handleAddToCart(cate, good, num) { //添加到购物车
				const index = this.cart.findIndex(item => {
					if (good.specConfig == 1) {
						return (item.id === good.id) && (item.props_text === good.props_text)
					} else {
						return item.id === good.id
					}
				})
				if (index > -1) {
					this.cart[index].number += num
				} else {	
					this.cart.push({
						id: good.id,
						cate_id: cate.id,
						name: good.productName,
						price: good.salePrice,
						number: num,
						itemId: good.itemId,
						image: good.productImg,
						use_property: good.specConfig,
						props_text: good.props_text,
						props: good.props
					})
				}
			},
			handleReduceFromCart(item, good) {
				const index = this.cart.findIndex(item => item.id === good.id)
				this.cart[index].number -= 1
				if (this.cart[index].number <= 0) {
					this.cart.splice(index, 1)
				}
			},
			showGoodDetailModal(item, good) {
				this.good = JSON.parse(JSON.stringify({ ...good,
					number: 1
				}))
				this.category = JSON.parse(JSON.stringify(item))

				this.goodDetailModalVisible = true
			},
			closeGoodDetailModal() { //关闭饮品详情模态框
				this.goodDetailModalVisible = false
				this.category = {}
				this.good = {}
			},
			changePropertyDefault(index, key) { //改变默认属性值
				this.good.property[index].values.forEach(value => this.$set(value, 'is_default', 0))
				this.good.property[index].values[key].is_default = 1
				this.good.number = 1
			},
			getGoodSelectedProps(good, type = 'text') { //计算当前饮品所选属性
				if (good.specConfig == 1) {
					let props = []
					good.specs.forEach(({
						values
					}) => {
						values.forEach(value => {
							if (value.is_default) {
								props.push(type === 'text' ? value.value : value.id)
							}
						})
					})
					return type === 'text' ? props.join(',') : props
				}
				return ''
			},
			handlePropertyAdd() {
				this.good.number += 1
			},
			handlePropertyReduce() {
				if (this.good.number === 1) return
				this.good.number -= 1
			},
			handleAddToCartInModal() {
				const product = Object.assign({}, this.good, {
					props_text: this.getGoodSelectedProps(this.good),
					props: this.getGoodSelectedProps(this.good, 'id')
				})
				this.handleAddToCart(this.category, product, this.good.number)
				this.closeGoodDetailModal()
			},
			openCartPopup() { //打开/关闭购物车列表popup
				this.cartPopupVisible = !this.cartPopupVisible
			},
			handleCartClear() { //清空购物车
				uni.showModal({
					title: '提示',
					content: '确定清空购物车么',
					success: ({
						confirm
					}) => {
						if (confirm) {
							this.cartPopupVisible = false
							this.cart = []
						}
					}
				})
			},
			handleCartItemAdd(index) {
				this.cart[index].number += 1
			},
			handleCartItemReduce(index) {
				if (this.cart[index].number === 1) {
					this.cart.splice(index, 1)
				} else {
					this.cart[index].number -= 1
				}
				if (!this.cart.length) {
					this.cartPopupVisible = false
				}
			},
			toPay() {
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/pages/login/login'
					})
					return
				}

				uni.showLoading({
					title: '加载中'
				})
				
				//type 0 门票 1 百货
				// let cartData = {
				// 	type:0,
				// 	detail:this.cart
				// }
				// uni.setStorageSync('cart', cartData)
				// uni.setStorageSync('cart', JSON.parse(JSON.stringify(this.cart)))

				let data = [];
				for (let i=0,len = this.cart.length;i<len;i++) {
				    data.push({
						productId: this.cart[i].id,
						itemId: this.cart[i].itemId,
						specContent: '',
						count: this.cart[i].number
					})
				}
							
				addCart(data).then(res => {
					uni.hideLoading()
					uni.navigateTo({
						url: '/pages/order/pay/index'
					})
				}, error => {
					uni.hideLoading();
				});
			},
			handleClick(e) {
				let index = e.index;
				if (index === 0) {
					this.errorModel = false;
				} else {
					this.errorModel = false;
					this.selectStore();
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import '~@/pages/tabbar/ticket/menu.scss';
</style>
